package model

import (
	"gzstore/dao"
	"strconv"
)

//Book 书籍结构体
type Book struct {
	ID      int
	Title   string
	Author  string
	Price   float64
	Sales   int
	Stock   int
	ImgPath string
}

func GetBooks() (books *[]Book, err error) {
	err = dao.DB.Find(books).Error
	return
}

//GetPageBooks 通过页码，获取每页数据
func GetPageBooks(pageNo string) (*Page, error) {
	//转换传入的数据
	iPageNo, err := strconv.ParseInt(pageNo, 10, 64) //转换的字符串pageNo，进制数10，类型int64
	if err != nil {
		return nil, err
	}
	//sql查询有多少条数据
	// sqlStr := "select count(*) from books"
	// row := utils.Db.QueryRow(sqlStr)
	// row.Scan(&totalRecord)
	//创建变量接收总条数
	var totalRecord int64
	err = dao.DB.Find(&Book{}).Count(&totalRecord).Error
	if err != nil {
		return nil, err
	}
	//根据总条数得到分页总数
	var pageSize int64 = 4 //定义每页多少条，这里之所以没有:=是因为Page那里是int64,而:=是int
	var totalPageNo int64
	if totalRecord%pageSize == 0 { //这里取余，为0直接赋值，不为0就+1
		totalPageNo = totalRecord / pageSize
	} else {
		totalPageNo = totalRecord/pageSize + 1
	}
	//根据传入页数查询当前页数据
	// sqlStr2 := "SELECT id, title, author, price, sales, stock, img_path FROM books limit ?,?"
	// rows, err := utils.Db.Query(sqlStr2, (iPageNo-1)*pageSize, pageSize)
	var books []Book
	err = dao.DB.Limit(int(pageSize)).Offset(int((iPageNo - 1) * pageSize)).Find(&books).Error
	if err != nil {
		return nil, err
	}

	//最后把书籍信息及相关页数总数信息写入page结构体
	page := &Page{
		Books:       books,
		PageNo:      iPageNo,
		PageSize:    pageSize,
		TotalPageNo: totalPageNo,
		TotalRecord: totalRecord,
	}
	return page, nil
}
